import wepy from 'wepy'
import config from '../utils/config'

// 上传请求的封装
export async function wxUpload(tempFilePath, callback) {
  if (!tempFilePath) {
    console.log('无效的文件')
    return false
  }
  wepy.showLoading({
    title: '上传中'
  })
  let uploadResult = {}
  try {
    uploadResult = await wepy.uploadFile({
      url: `${config.API_URL}/upload`,
      filePath: tempFilePath,
      header: {
        'content-type': 'multipart/form-data'
      },
      name: 'file'
    })
  } catch (e) {
    wepy.showToast({
      title: '网络出错',
      icon: 'fail',
      duration: 1000
    })
    return
  }
  wepy.hideLoading()
  const data = JSON.parse(uploadResult.data)
  if (data && data.code === 0) {
    callback && callback(data)
  }
}

// 补零
export function toDub (n) {
  return n < 10 ? `0${n}` : `${n}`
}
